﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Runtime.Serialization;

 

namespace Meraz.Web.Filters
{
    public class ObjectFilter : ActionFilterAttribute
    {

        public string Param { get; set; }

        public Type RootType { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            //move current position in the stream back to the beginning
            filterContext.HttpContext.Request.InputStream.Position = 0;
            if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json"))
            {

                object o =

                new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);

                filterContext.ActionParameters[Param] = o;

            }

            else
            {

                var xmlRoot = XElement.Load(new StreamReader(filterContext.HttpContext.Request.InputStream,

                filterContext.HttpContext.Request.ContentEncoding));

                object o = new XmlSerializer(RootType).Deserialize(xmlRoot.CreateReader());

                filterContext.ActionParameters[Param] = o;

            }

        }

    }
}